<template>
  <div>
    <h3>上游DNS设置</h3>
    <el-form ref="form" :model="localUpstreamDns" :rules="rules" label-width="160px">
      <el-form-item label="上游DNS服务器" prop="server">
        <el-input v-model="localUpstreamDns.server" placeholder="请输入上游DNS服务器地址"></el-input>
      </el-form-item>
      <el-form-item label="端口" prop="port">
        <el-input-number v-model="localUpstreamDns.port" :min="1" :max="65535"></el-input-number>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存设置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: ['upstreamDns'],
  data() {
    return {
      localUpstreamDns: { ...this.upstreamDns },
      rules: {
        server: [
          { required: true, message: '请输入上游DNS服务器地址', trigger: 'blur' },
          { pattern: /^(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(?::\d+)?$/, message: '请输入有效的DNS服务器地址', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'change' },
          { type: 'number', min: 1, max: 65535, message: '端口号必须在1到65535之间', trigger: 'change' }
        ]
      }
    };
  },
  watch: {
    upstreamDns: {
      handler(newVal) {
        this.localUpstreamDns = { ...newVal };
      },
      deep: true
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('save-settings', this.localUpstreamDns);
        } else {
          this.$message({
            type: 'error',
            message: '请检查表单填写是否正确'
          });
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
h3 {
  margin-bottom: 20px;
}

.el-form {
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>
